package org.opens.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ClassPathResource;

import java.io.*;

public class ReadClassPathFileUtil {

    public static String readAsString(String path) {
        FileInputStream fileInputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;

        try {
            ClassPathResource classPathResource = new ClassPathResource(path);
            File file = classPathResource.getFile();
            fileInputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(fileInputStream);
            bufferedReader = new BufferedReader(inputStreamReader);

            StringBuilder stringBuilder = new StringBuilder();

            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }

            return stringBuilder.toString();
        } catch (IOException e) {
            //
        } finally {
            IoUtil.close(bufferedReader);
            IoUtil.close(inputStreamReader);
            IoUtil.close(fileInputStream);
        }

        return null;
    }

    /**
     * 读取classpath下面的文件为文件对象
     * @param path classpath下的路径
     */
    public static File readAsFile(String path) {
        ClassPathResource classPathResource = new ClassPathResource(path);
        return classPathResource.getFile();
    }

    public static String read(String path) {
        FileInputStream fileInputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;

        try {
            ClassPathResource classPathResource = new ClassPathResource(path);
            File file = classPathResource.getFile();
            fileInputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(fileInputStream);
            bufferedReader = new BufferedReader(inputStreamReader);

            StringBuilder stringBuilder = new StringBuilder();

            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }

            return stringBuilder.toString();
        } catch (IOException e) {
            //
        } finally {
            IoUtil.close(bufferedReader);
            IoUtil.close(inputStreamReader);
            IoUtil.close(fileInputStream);
        }

        return null;
    }

}
